package com.ayjsolutions.marcadoresfutbol;

import java.util.ArrayList;
import java.util.List;

import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.ActionProvider;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.ayjsolutions.marcadoresfutbol.database.DBPartidosLista;
import com.ayjsolutions.marcadoresfutbol.service.ResultsReceiver;
import com.ayjsolutions.marcadoresfutbol.service.UpdateService;
import com.ayjsolutions.marcadoresfutbol.util.Utiles;

public class MainActivity extends SherlockListActivity implements
		ActionBar.TabListener {

	private MenuItem refresh;
	public static ListActivity activity;

	public static String DIRECTO = "directo";
	public static String PROGRAMADOS = "programados";
	public static String TERMINADOS = "terminados";
	public static String ALERTAS = "alertas";
	public int REPEAT_TIME = 30 * 1000;

	private UpdateService updateService;

	public static Drawable divider;

	public static DBPartidosLista basedatos;

	public static List<String> ligasMostrar = new ArrayList<String>();
	public static String status;

	private ExpandableListAdapter mAdapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activity = this;

		doBindService();

		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		basedatos = new DBPartidosLista(this);

		Editor edit = preferences.edit();

		edit.putString("status", DIRECTO);
		edit.putString("DIRECTO", DIRECTO);
		edit.putString("PROGRAMADOS", PROGRAMADOS);
		edit.putString("ALERTAS", ALERTAS);

		edit.commit();

		getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// We create the tabs

		// Tab en directo
		ActionBar.Tab tab = getSupportActionBar().newTab();
		tab.setText(R.string.en_directo);
		tab.setTabListener(this);
		tab.setTag(DIRECTO);
		getSupportActionBar().addTab(tab);

		// Tab programados
		tab = getSupportActionBar().newTab();
		tab.setText(R.string.programados);
		tab.setTabListener(this);
		tab.setTag(PROGRAMADOS);
		getSupportActionBar().addTab(tab);

		// Tab alertas
		tab = getSupportActionBar().newTab();
		tab.setText(R.string.alertas);
		tab.setTag(ALERTAS);
		tab.setTabListener(this);
		getSupportActionBar().addTab(tab);

	}

	@Override
	public void onPause() {
		super.onPause();
		basedatos.close();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unbindService(mConnection);
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction transaction) {
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction transaction) {

		// This method will be called when the app is opened for the first time
		// and when the tab is changed

		List<PartidoLista> partidos = StartActivity.partidos;
		List<PartidoLista> partidosMostrar = new ArrayList<PartidoLista>();
		Editor edit = PreferenceManager.getDefaultSharedPreferences(
				MainActivity.activity).edit();

		if (tab.getTag().equals(PROGRAMADOS)) {
			edit.putString("status", PROGRAMADOS);
		} else if (tab.getTag().equals(DIRECTO)) {
			edit.putString("status", DIRECTO);
		} else if (tab.getTag().equals(ALERTAS)) {
			edit.putString("status", ALERTAS);
		}

		edit.commit();

		basedatos = new DBPartidosLista(this);
		basedatos.open();
		ArrayList<String> ligasDirecto = basedatos.getLigasDirecto();

		if (!PreferenceManager.getDefaultSharedPreferences(this)
				.getString("status", ALERTAS).equals(ALERTAS)) {
			for (PartidoLista partido : partidos) {

				// We show it if necessary

				if (PreferenceManager.getDefaultSharedPreferences(this)
						.getString("status", DIRECTO).equals(DIRECTO)) {
					if ((partido.getHomeTeam().equals("liga") && ligasDirecto
							.contains(partido.getLiga()))
							|| (ligasMostrar.contains(partido.getLiga()) && partido
									.getTime().contains("'"))) {
						// We show only the league names and the matches
						// of the leagues to be shown that are currently active
						partidosMostrar.add(partido);
					}
				} else {
					if (partido.getHomeTeam().equals("liga")
							|| (ligasMostrar.contains(partido.getLiga()))) {
						// We show all the matches of the leagues to show
						// and the names of all the leagues
						partidosMostrar.add(partido);
					}
				}
			}
		} else {
			List<PartidoLista> partidosToUpdate = basedatos
					.getPartidosToUpdate();

			if (!partidosToUpdate.isEmpty()) {
				PartidoLista liga = new PartidoLista();
				liga.setTime("liga");
				liga.setHomeGoals("liga");
				liga.setVisitorGoals("liga");
				liga.setVisitorTeam("liga");
				liga.setHomeTeam("liga");
				liga.setTime("liga");
				liga.setURL("liga");
				liga.setLiga(partidosToUpdate.get(0).getLiga());
				partidosMostrar.add(liga);

				for (int i = 0; i < partidosToUpdate.size(); i++) {
					if (i > 0
							&& !partidosToUpdate
									.get(i)
									.getLiga()
									.equals(partidosToUpdate.get(i - 1)
											.getLiga())) {
						liga = new PartidoLista();
						liga.setTime("liga");
						liga.setHomeGoals("liga");
						liga.setVisitorGoals("liga");
						liga.setVisitorTeam("liga");
						liga.setHomeTeam("liga");
						liga.setTime("liga");
						liga.setURL("liga");
						liga.setLiga(partidosToUpdate.get(i).getLiga());
						partidosMostrar.add(liga);
					}
					partidosMostrar.add(partidosToUpdate.get(i));
				}
			}
		}

		// Database saved for debugging purposes
		Utiles.savedatabase();

		// We have the matches list and we add it to the activity
		ListaPartidosAdapter lista = new ListaPartidosAdapter(this,
				partidosMostrar);
		setListAdapter(lista);

		// This method will be called every time an item is long pressed
		// Functionality will be added in the future
		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int pos, long id) {
				// TODO Auto-generated method stub

				ListaPartidosAdapter lista = (ListaPartidosAdapter) activity
						.getListAdapter();

				basedatos.open();

				int state = basedatos.changeStatePartido(lista.partidos
						.get(pos));

				lista.partidos.get(pos).setFollow(Integer.toString(state));

				basedatos.close();

				ImageView campana = (ImageView) arg1.findViewById(R.id.campana);

				if (state == 0) {
					campana.setVisibility(View.INVISIBLE);
				} else {
					campana.setVisibility(View.VISIBLE);
				}

				lista.notifyDataSetChanged();

				return true;
			}
		});

		AlarmManager service = (AlarmManager) this
				.getSystemService(Context.ALARM_SERVICE);
		Intent i = new Intent(this, ResultsReceiver.class);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(
				this.getApplicationContext(), 0, i, 0);
		service.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
				+ (5 * 1000), pendingIntent);

		basedatos.close();
		edit.commit();

	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction transaction) {
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		ListaPartidosAdapter lista = (ListaPartidosAdapter) getListAdapter();

		PartidoLista partidoActual = lista.partidos.get(position);

		basedatos.open();
		List<PartidoLista> partidosLiga = basedatos.getPartidosFromLiga(
				partidoActual.getLiga(),
				PreferenceManager.getDefaultSharedPreferences(this).getString(
						"status", DIRECTO));

		if (partidoActual.getHomeTeam().equals("liga")) {
			if (!ligasMostrar.contains(partidoActual.getLiga())
					&& partidoActual.getHomeTeam().equals("liga")) {

				// If a league is clicked, then the matches are shown
				lista.partidos.addAll(position + 1, partidosLiga);
				ligasMostrar.add(partidoActual.getLiga());
			} else {

				// If it is clicked again, we hide the matches
				ligasMostrar.remove(partidoActual.getLiga());
				for (int i = 0; i < partidosLiga.size(); i++) {
					lista.partidos.remove(position + 1);
				}
			}
		} else {
			Intent intent = new Intent(activity, Partido.class);
			startActivity(intent);
		}

		basedatos.close();

		lista.notifyDataSetChanged();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.refresh, menu);

		// refresh menu item
		refresh = menu.findItem(R.id.menu_item_action_provider_action_bar);

		return super.onCreateOptionsMenu(menu);
	}

	public static class Refresh extends ActionProvider {

		/** Context for accessing resources. */
		private final Context mContext;

		/**
		 * Creates a new instance.
		 * 
		 * @param context
		 *            Context for accessing resources.
		 */
		public Refresh(Context context) {
			super(context);
			mContext = context;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public View onCreateActionView() {
			// Inflate the action view to be shown on the action bar.
			LayoutInflater layoutInflater = LayoutInflater.from(mContext);
			View view = layoutInflater.inflate(R.layout.layout_refresh, null);
			ImageButton button = (ImageButton) view.findViewById(R.id.button);
			// Attach a click listener for launching the system settings.
			button.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {

					Utiles.refreshPartidos((MainActivity) activity, 0);

				}
			});
			return view;
		}

	}

	private ServiceConnection mConnection = new ServiceConnection() {

		public void onServiceConnected(ComponentName className, IBinder binder) {
			updateService = ((UpdateService.MyBinder) binder).getService();
		}

		public void onServiceDisconnected(ComponentName className) {
			updateService = null;
		}
	};

	void doBindService() {
		bindService(new Intent(this, UpdateService.class), mConnection,
				Context.BIND_AUTO_CREATE);
	}
	
	@Override
	public void onBackPressed() {

		Log.w("Back", "Back was pressed. Finishing the app... (hopefully)");
		setResult(0);
		finish();
	}

}
